using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using ShopForWeb.Dtos.BasicView;
using ShopForWeb.Dtos.ViewModel;
using ShopForWeb.Models.Basic;
using ShopForWeb.Models.DbContexts;

namespace ShopForWeb.Services
{
  public class ProductServices
  {
    private ShopDbContext _Db;
    private IMapper _Mapper;

    public ProductServices(ShopDbContext db, IMapper mapper)
    {
      this._Db = db;
      this._Mapper = mapper;
    }
    public async Task<int> AddNewAsync(Product product)
    {
      var entity = _Db.Entry<Product>(product);
      entity.State = EntityState.Added;
      return await _Db.SaveChangesAsync();
    }

    public async Task<int> UpdateAsync(Product product)
    {
      _Db.Entry<Product>(product).State = EntityState.Modified;
      return await _Db.SaveChangesAsync();
    }

    public async Task<int> DeleteAsync(int productId)
    {
      var o = _Db.Entry<Product>(new Product
      {
        ProductId = productId
      });
      o.State = EntityState.Deleted;
      return await _Db.SaveChangesAsync();
    }

    public async Task<int> UpdatePhotoAsync(Product product)
    {
      var e = _Db.Entry<Product>(product);
      e.Property("Photo").IsModified = true;
      return await _Db.SaveChangesAsync();
    }
    public async Task<List<ProductView>> GetByPriceAsync(decimal price)
    {
      var query = _Db.ProductSet.Where(p => p.Price > price)
      .OrderBy(p => p.Price);

      var list = await query.ToListAsync<Product>();

      return _Mapper.Map<List<ProductView>>(list);
    }

    public async Task<PageView<ProductView>> GetPageAsync(int page, int size)
    {
      PageView<ProductView> result = new PageView<ProductView>();
      var query = _Db.ProductSet.Skip((page - 1) * size).Take(size);
      result.Data = _Mapper.Map<List<ProductView>>(await query.ToListAsync<Product>());
      result.Total = await _Db.ProductSet.CountAsync();
      return result;
    }
    public async Task<ProductView?> GetByIdAsync(int productId)
    {
      var query = _Db.ProductSet.Where(p => p.ProductId == productId);
      var result = await query.FirstOrDefaultAsync();
      if (result == null) return null;
      return _Mapper.Map<ProductView>(result);
    }
  }
}
